package com.alpha.module.user.service.impl;

import com.alpha.common.utils.BusinessException;
import com.alpha.common.utils.PageUtils;
import com.alpha.components.AccountFundsService;
import com.alpha.module.user.dao.AccountMapper;
import com.alpha.module.user.entity.Account;
import com.alpha.module.user.entity.User;
import com.alpha.module.user.service.AccountService;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;


@Service("accountService")
public class AccountServiceImpl implements AccountService {

    private final AccountMapper accountMapper;
    private final AccountFundsService fundsService;

    public AccountServiceImpl(AccountMapper accountMapper, AccountFundsService fundsService) {
        this.accountMapper = accountMapper;
        this.fundsService = fundsService;
    }

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        List<Account> list = null;
        return new PageUtils(new PageInfo<>(list));
    }

    @Override
    public Account getById(Long id) {
        if (id <= 0) {
            throw new BusinessException("参数错误");
        }
        return accountMapper.selectByPrimaryKey(id);
    }

    @Override
    public void updateById(Account account) {
            accountMapper.updateByPrimaryKeySelective(account);
    }

    @Transactional(rollbackFor = {Exception.class})
    @Override
    public void save(Account account) throws BusinessException {

    }

    @Transactional
    @Override
    public void saveByUser(User user) {
        Account account = this.accountMapper.selectByUserId(user.getId());
        if (account == null) {
            account = new Account();
            account.setUserId(user.getId());
            account.setBalance(BigDecimal.ZERO);
            account.setIntegral(0);
            account.setTotalAmount(BigDecimal.ZERO);
            this.accountMapper.insertSelective(account);
            this.fundsService.encryptAccount(account.getId());
        }
    }

    @Transactional
    public void updateAccount(Account account) {
        if(fundsService.checkAccount(account.getId())) {
            int i = accountMapper.updateByPrimaryKeySelective(account);
            if(i<1) {
                throw new BusinessException("资金异常");
            }
            this.fundsService.encryptAccount(account.getId());
        } else {
            throw new BusinessException("账户异常，请联系管理员");
        }
    }

}